package io.shallwe._admin.line;
/**
   *  下线扫描服务
 * @author 王小伟
 * @date   2019-06-10 21:17:33 
 */

import java.awt.print.*;
import java.util.Date;
import java.util.List;

import com.jfinal.aop.Aop;
import io.shallwe._admin.basedata.hangerframe.HangerFrameService;
import io.shallwe.common.model.*;
import org.apache.commons.lang3.StringUtils;

import com.jfinal.aop.Inject;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import io.shallwe._admin.basedata.scanner.ScannerService;

public class ExitScanService {
	LineInfoService lineInfoService = Aop.get(LineInfoService.class);
	ScannerService scannerService = Aop.get(ScannerService.class);
	
	private ExitBuffer dao = ExitBuffer.dao;
	private ExitScan exitScanDao = new ExitScan().dao();
	public ExitBuffer findById(String id) {
		return dao.findById(id);
	}
	
	public ExitBuffer findByRackNo(String hangerNo) {
		String sql="select top 1 * from t_exit_buffer where hanger_no = ? and status_flag=0";
		return dao.findFirst(sql,hangerNo);
	}


	/**
	 * 查询下线缓冲区的数据
	 * @return
	 */
	public List<ExitBuffer> listAllValidBufferData(){
		return dao.template("exitBuffer.listAllValidBufferData").find();
	}

	/**
	 * 查询下线扫描暂存表的数据
	 * @return
	 */
	public  List<ExitScan> listAllValidScanData(){
		return exitScanDao.template("exitBuffer.listAllValidScanData").find();
	}
	
	public Ret paginate() {
		Page<Record> paginate = Db.template("exitBuffer.paginate").paginate(1, 100);
		return Ret.ok("total", paginate.getTotalRow()).set("rows", paginate.getList());
	}
	
	public List<Record> exitBufferInfo() {
		Page<Record> paginate = Db.template("exitBuffer.paginate").paginate(1, 100);
		return paginate.getList();
	}
	
	public Ret save(ExitBuffer exitBuffer,String accountId) {
		if(isRackNoExists(exitBuffer.getHangerNo(),-1)) {
			return Ret.fail("msg","电泳框编号已经存在，请输入其他的电泳框编号");
		}
		

		exitBuffer.setAccountId(accountId);
		exitBuffer.setUpdateTime(new Date());

		exitBuffer.save();
		return Ret.ok("msg","操作成功");	
	}
	
	public Ret update(ExitBuffer exitBuffer,String accountId) {
		if(isRackNoExists(exitBuffer.getHangerNo(),exitBuffer.getId())) {
			return Ret.fail("msg","电泳框编号已经存在，请输入其他的电泳框编号");
		}

		exitBuffer.setAccountId(accountId);
		exitBuffer.setUpdateTime(new Date());
		exitBuffer.update();
		return Ret.ok("msg","操作成功");	
	}
	
	public Ret delete(String id,int type) {
		if(type==1){
			dao.deleteById(id);
		}
		if(type==2) {
			exitScanDao.deleteById(id);
		}
		return Ret.ok("msg","操作成功");
	}
	
	
	public boolean isRackNoExists(String hangerNo,Integer id) {
		hangerNo=hangerNo.toLowerCase().trim();
		String sql="select top 1 id from t_exit_buffer where lower(hanger_no) = ? and id != ?";
		return Db.queryStr(sql,hangerNo,id)!=null;
	}


	public Ret scan(String code,String ip) {

		Scanner scanner = scannerService.findByIp(ip);
		if(scanner!=null) {
			ScannerRecord scannerRecord = new ScannerRecord().setUpdateTime(new Date());
			scannerRecord.setScannerId(scanner.getId());
			scannerRecord.setScannerType(scanner.getScannerType());
			scannerRecord.setRawText(code).setHangerNo("");
			scannerRecord.setManualFlag(ScannerRecord.MANUAL_SCAN);
			scannerRecord.setStatusFlag(ScannerRecord.INIT);
			if (StringUtils.startsWith(code, "U#")) {
				String employeeNumber = StringUtils.substringAfter(code, "U#");
				scannerService.bindAccountByIp(ip, employeeNumber);
			} else if (StringUtils.startsWith(code, "R")) {
				scanHangerNo(code, ip);
				scannerRecord.setHangerNo(code);
			} else if (StringUtils.startsWith(code, "FF")) {
				scanVehicleNo(code, ip);
			} else {
				//do nothing
			}
			scannerRecord.save();
		}
		return Ret.ok("msg","操作成功");
	}



	private ExitScan completeExitScan(ExitScan exitScan){
		String hangerNo = exitScan.getHangerNo();
		ExitBuffer buffer = dao.template("exitBuffer.findExitBuffer", hangerNo).findFirst();
		if(buffer!=null){
			exitScan.setBarcode(buffer.getBarcode()).setMaterialCount(buffer.getMaterialCount());
			exitScan.setTraceNo(buffer.getTraceNo()).setMaterialNo(buffer.getMaterialNo());
			exitScan.setFrameNo(buffer.getFrameNo());
			exitScan.setAccountId(buffer.getAccountId());
		}
		return exitScan;
	}

	public void scanHangerNo(String hangerNo, String ip) {
		ExitScan exitScan = exitScanDao.template("exitBuffer.findExitScan", ip).findFirst();
		String exitAccountId = scannerService.getAccountIdByScannerId(ip);
		if(exitAccountId==null){
			exitAccountId="";
		}

		if(exitScan==null){
			exitScan = new ExitScan().setHangerNo(hangerNo).setExitAccountId(exitAccountId).setIpAddress(ip);
			exitScan= this.completeExitScan(exitScan);
			exitScan.setCreateTime(new Date()).setStatusFlag(1).save();
			return;
		}
		exitScan .setHangerNo(hangerNo);
		exitScan= this.completeExitScan(exitScan).setUpdateTime(new Date());
		if(StrKit.isBlank(exitScan.getVehicleNo())){
			exitScan .setExitAccountId(exitAccountId);
			exitScan.update();
			return;
		}

		//创建周转车 移除缓冲区信息 更新扫描表
		exitScan.setExitAccountId(exitAccountId);
		this.updateVehicleInfo(exitScan);
	}
	
	/**
	 * 扫描周转车信息
	 * @param vehicleNo
	 * @param ip
	 */
	public void scanVehicleNo(String vehicleNo,String ip) {
		ExitScan exitScan = exitScanDao.template("exitBuffer.findExitScan", ip).findFirst();
		String exitAccountId = scannerService.getAccountIdByScannerId(ip);
		if(exitAccountId==null){
			exitAccountId="";
		}

		if(exitScan==null){
			exitScan = new ExitScan().setIpAddress(ip).setVehicleNo(vehicleNo).setExitAccountId(exitAccountId);
			exitScan= this.completeExitScan(exitScan);
			exitScan.setCreateTime(new Date()).setStatusFlag(1).save();
			return;
		}
		exitScan.setVehicleNo(vehicleNo);
		exitScan= this.completeExitScan(exitScan).setUpdateTime(new Date());
		if(StrKit.isBlank(exitScan.getHangerNo())){
			exitScan.setExitAccountId(exitAccountId);
			exitScan.update();
			return;
		}
		exitScan.setExitAccountId(exitAccountId);
		this.updateVehicleInfo(exitScan);
	}


	public void updateVehicleInfo(ExitScan exitScan){
		exitScan.setUpdateTime(new Date());
		exitScan.setStatusFlag(2).update();
		ExitBuffer buffer = dao.template("exitBuffer.findExitBuffer", exitScan.getHangerNo()).findFirst();
		if(buffer!=null){
			buffer.setUpdateTime(new Date()).setStatusFlag(2).update();
			TurnoverVehicle vehicle = new TurnoverVehicle();
			vehicle.setMaterialNo(exitScan.getMaterialNo())
					.setHangerNo(exitScan.getHangerNo())
					.setFrameNo(exitScan.getFrameNo())
					.setBarcode(exitScan.getBarcode())
					.setFrameNo(exitScan.getFrameNo())
					.setCreateTime(new Date())
					.setVehicleNo(exitScan.getVehicleNo())
					.setAccountId(exitScan.getAccountId())
					.setExitAccountId(exitScan.getExitAccountId())
					.setStatusFlag(1)
					.setTraceNo(exitScan.getTraceNo())
					.setVehicleNo(exitScan.getVehicleNo())
					.setMaterialCount(exitScan.getMaterialCount());
			vehicle.save();
		}
	}

	
	/**
	  * 下线自动扫描枪扫描
	 * @param code
	 */
	public void autoScan(String code) {
		if(StringUtils.startsWith(code, "R")==false){
			return;
		}
		Scanner autoautoOfflineScannerlineScanner = scannerService.findAutoOfflineScanner();
		if(autoautoOfflineScannerlineScanner!=null){
			ScannerRecord scannerRecord = new ScannerRecord();
			scannerRecord.setHangerNo(code)
					.setManualFlag(ScannerRecord.MANUAL_SCAN)
					.setStatusFlag(ScannerRecord.INIT)
					.setUpdateTime(new Date())
					.setScannerId(autoautoOfflineScannerlineScanner.getId())
					.setScannerType(autoautoOfflineScannerlineScanner.getScannerType())
					.setRawText(code).save();
		}
	}

	public  void doAutoScan(String code){
		LineInfo lineInfo = lineInfoService.findByHangerNo(code);
		if(lineInfo==null) {
			return;
		}

		String traceNo = lineInfo.getTraceNo();
		if(StrKit.isBlank(lineInfo.getBarcode())) {
			return;
		}
		String materialNo = lineInfo.getMaterialNo();
		String frameNo = lineInfo.getFrameNo();
		String barcode = lineInfo.getBarcode();
		String accountId = lineInfo.getAccountId();
		Integer materialCount = lineInfo.getMaterialCount();
		if (frameNo==null){
			frameNo="";
		}
		if (barcode==null){
			barcode="";
		}
		if (traceNo==null){
			traceNo="";
		}if (materialNo==null){
			materialNo="";
		}
		if (accountId==null){
			accountId="";
		}
		if (barcode==null){
			barcode="";
		}

		if(materialCount==null){
			materialCount=0;
		}
		ExitBuffer buffer = this.findByRackNo(code);
		if (buffer == null) {
			buffer = new ExitBuffer();
			buffer.setTraceNo(traceNo)
					.setHangerNo(code)
					.setFrameNo(frameNo)
					.setMaterialNo(materialNo)
					.setBarcode(barcode)
					.setCreateTime(new Date())
					.setUpdateTime(new Date())
					.setAccountId(accountId);
			if(materialCount>0){
				buffer.setMaterialCount(materialCount);
			}
			buffer.setStatusFlag(1);
			buffer.save();

		} else {
			buffer.setTraceNo(lineInfo.getTraceNo())
					.setHangerNo(code)
					.setFrameNo(lineInfo.getFrameNo())
					.setUpdateTime(new Date())
					.setMaterialNo(materialNo)
					.setBarcode(barcode)
					.setAccountId(accountId);
			if(materialCount>0){
				buffer.setMaterialCount(materialCount);
			}
			buffer.update();
		}
		lineInfo.setTraceNo("");
		lineInfo.setUpdateTime(new Date());
		lineInfo.setAccountId("");
		lineInfo.setMaterialNo("");
		lineInfo.setBarcode("");
		lineInfo.setMaterialCount(0);
		lineInfo.update();
	}

	/**
	 * @Description: 下线扫码枪匹配了
	 * @param:  [materialCode, materialCount, traceCode, barCode]
	 * @return: void
	 * @author : gkw
	 */
	private void printCodeSheet(String materialCode,Integer materialCount, String traceCode, String barCode){
		String materialName="";
		if(materialCode ==null){
			materialCode="";
		}else{
			if(StringUtils.isNotBlank(materialCode)){
				String materialSql="SELECT remark FROM t_material_code_name WHERE materialCode= ?";
				Record materialNameR=Db.findFirst(materialSql,materialCode);
				if(materialNameR!=null){
					String tempName=materialNameR.getStr("remark");
					if(StringUtils.isNotBlank(tempName)){
						materialName=tempName;
					}
				}
			}
		}
		if(materialCount ==null){
			materialCount=Integer.valueOf(0);
		}
		if(traceCode ==null){
			traceCode="";
		}
		if(barCode ==null){
			barCode="";
		}

		PrinterJob job = PrinterJob.getPrinterJob();
		//弹出选择打印机页面，可隐藏
//		if (!job.printDialog()) {
//			return;
//		}
		double margin=10;

		//用book后期能实现多页打印
		Book printBook = new Book();
		//设置纸张大小
		Paper paper=new Paper();
		paper.setImageableArea(margin, margin, paper.getWidth() - margin * 2, paper.getHeight() - margin * 2);

		PageFormat pf = new PageFormat();
		pf.setPaper(paper);
		printBook.append(new TurnoverVehiclePrintModel(materialCode,materialName,materialCount.toString(),traceCode,barCode),pf);
		// 设置打印页
		job.setPageable(printBook);
		// 设置打印任务名称
		job.setJobName("多页打印");
		try{
			// 执行打印
			job.print();
		}catch (PrinterException e){
			e.printStackTrace();
		}

	}
}
